// components/widget-order/index.js
import api from "../../api/index.js";
import Message from 'tdesign-miniprogram/message/index';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsId: { //商品id
      type: String,
      value: ''
    },
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      this.setData({
        container: () => wx.createSelectorQuery().select('#container'),
      });
    },
    detached: function () {},
    onReady() {}
  },
  /**
   * 组件的初始数据
   */
  data: {
    goodsDetails: { //商品详情
      price: 0,
      goodsAttrPOS: []
    }, //商品详情
    selectedSpecOptions: { //用于记录选择的规格参数
      selectedSpecName: "",
      selectedSpecNameId: "",
      quantity: 1, //数量 
      totalPrice: 0, //总价
      specOptions: [] //选中的对象数组{goodsAttrId,goodsAttrName,goodsAttrValueId,goodsAttrValueName}
      //动态属性: 规格id VS 规格值id
    },
    // -----------------------------------------------推荐组合-----------------------------
    hotCombination: [],
    //--------------------------内嵌组件2-----------------------------------------------
    innerPopVisible: false
  },
  // 组件数据字段监听器，用于监听 properties 和 data 的变化
  observers: {
    'goodsId': function (show) {
      if (show === '') {
        return;
      }
      if (show === '0') {
        return;
      }
      //拉去数据
      this.initData(this.data.goodsId)
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    initData(goodsId) {
      //清空数据
      api.goodsDetails({
        id: goodsId,
        method: "get"
      }).then((res) => {
        this.setData({
          goodsDetails: res.data,
        }, this.initSelectSpec(goodsId, res.data))
      })
      this.getHotCombination(this.data.goodsId)
    },
    initSelectSpec(goodsId, rawGoodsDetails) {
      let selectedSpecOptions = {
        quantity: 1, //数量 
        totalPrice: rawGoodsDetails.price, //总价
        specOptions: [] //选中的对象
      }
      let shopCart = getApp().globalData.shopCart
      let selectGoods = shopCart.goodsList[goodsId];
      if (selectGoods) { //从购物车中选择其中一个规格作为默认值
        let goodsIdNameKey = Object.keys(selectGoods.goodsIdNames)[0];
        selectedSpecOptions.selectedSpecName = goodsIdNameKey.split("_")[1]
        let goodsIdNameValue = Object.values(selectGoods.goodsIdNames)[0];
        selectedSpecOptions.quantity = goodsIdNameValue.goodsNameNum
        selectedSpecOptions.totalPrice = (goodsIdNameValue.goodsNameNum * goodsIdNameValue.goodsNamePrice).toFixed(1)
        let nameIds = goodsIdNameValue.nameId.split("|")
        // const nameId = selectedSpecOptions.specOptions.map(i => i.goodsAttrId + ":" + i.goodsAttrName + ":" + i.goodsAttrValueId + ":" + i.goodsAttrValueName).join('|');
        for (var i = 0; i < nameIds.length; i++) {
          let vv = nameIds[i].split(":");
          selectedSpecOptions.specOptions[i] = {
              goodsAttrId: vv[0],
              goodsAttrName: vv[1],
              goodsAttrValueId: vv[2],
              goodsAttrValueName: vv[3]
            },
            selectedSpecOptions[vv[0]] = vv[2]
        }

      }
      this.setData({
        selectedSpecOptions
      })
    },
    // 选择规格
    selectSpec: function (e) {
      const idx1 = e.currentTarget.dataset.idx1;
      const idx2 = e.currentTarget.dataset.idx2;
      const goodsDetails = this.data.goodsDetails;
      //---------------------------------------
      //选择的
      const selectedSpecOptions = this.data.selectedSpecOptions;
      //新增动态属性（选择效果）
      selectedSpecOptions[goodsDetails.goodsAttrPOS[idx1].id] = goodsDetails.goodsAttrPOS[idx1].goodsAttrValues[idx2].id
      selectedSpecOptions.specOptions[idx1] = {
        goodsAttrId: goodsDetails.goodsAttrPOS[idx1].id,
        goodsAttrName: goodsDetails.goodsAttrPOS[idx1].attrName,
        goodsAttrValueId: goodsDetails.goodsAttrPOS[idx1].goodsAttrValues[idx2].id,
        goodsAttrValueName: goodsDetails.goodsAttrPOS[idx1].goodsAttrValues[idx2].attrValueName
      }
      //构造唯一的规格名称
      selectedSpecOptions.selectedSpecName = selectedSpecOptions.specOptions.map(i => i.goodsAttrValueName).join('|');
      this.setData({
        selectedSpecOptions: selectedSpecOptions
      });
    },
    // 增加数量
    increaseQuantity: function () {
      if (!this.checkSelectSpecIsOk()) {
        this.showMessage("请选择规格属性!!!")
        return
      }
      const quantity = this.data.selectedSpecOptions.quantity + 1;
      const price = this.data.goodsDetails.price;
      this.setData({
        'selectedSpecOptions.quantity': quantity,
        'selectedSpecOptions.totalPrice': (price * quantity).toFixed(1)
      });
    },

    // 减少数量
    decreaseQuantity: function () {
      if (this.data.quantity <= 1) return;
      if (!this.checkSelectSpecIsOk()) {
        this.showMessage("请选择规格属性!!!")
        return
      }
      const quantity = this.data.selectedSpecOptions.quantity - 1;
      const price = this.data.goodsDetails.price;
      this.setData({
        'selectedSpecOptions.quantity': quantity,
        'selectedSpecOptions.totalPrice': (price * quantity).toFixed(1)
      });
    },
    // 取消购物车 取消购物车
    canceToCart: function () {
      this.triggerEvent('canceToCart', {})
    },
    // 加入购物车
    addToCart: function () {
      //判断是否选择完毕
      const goodsDetails = this.data.goodsDetails
      const selectedSpecOptions = this.data.selectedSpecOptions
      if (!this.checkSelectSpecIsOk()) {
        this.showMessage("请选择规格属性!!!")
        return
      }
      //发布购物车更新事件  

      const nameId = selectedSpecOptions.specOptions.map(i => i.goodsAttrId + ":" + i.goodsAttrName + ":" + i.goodsAttrValueId + ":" + i.goodsAttrValueName).join('|');
      debugger
      const newGoods = {
        id: goodsDetails.id,
        name: goodsDetails.goodsName + "_" + selectedSpecOptions.selectedSpecName,
        nameId,
        num: this.data.selectedSpecOptions.quantity,
        unitPrice: goodsDetails.price
      }
      getApp().eventShopBus.emit("update", newGoods)
      this.triggerEvent('addToCard', newGoods)

    },
    checkSelectSpecIsOk() {
      const goodsDetails = this.data.goodsDetails
      const selectedSpecOptions = this.data.selectedSpecOptions
      let selectOk = false
      //判断是否选择完毕
      if (selectedSpecOptions.specOptions.length != goodsDetails.goodsAttrPOS.length) {
        selectOk = false
      } else {
        let findRes = selectedSpecOptions.specOptions.includes(undefined);
        if (findRes) {
          selectOk = false
        } else {
          selectOk = true
        }
      }
      return selectOk;
    },
    showMessage(message) {
      Message.error({
        context: this,
        offset: [90, 32],
        duration: 3000,
        content: message,
      });
    },
    //-----------------------------------推荐组合---------------------------------------------
    getHotCombination(goodsId) { //拉去数据
      api.getHotCombination({
        id: goodsId,
        method: "get"
      }).then((res) => {
        this.setData({
          hotCombination: res.data
        })
      })
    },
    onHotCombinationChange(e) {
      const {
        index,
        value,
        item
      } = e.detail;
      const hotCombination = this.data.hotCombination;
      hotCombination[index].num = value
      this.setData({
        hotCombination
      });
    },
    //------------------------------------嵌套弹框---------------------------------------------
    openInnerPopOrderCart: function () {
      this.setData({
        innerPopVisible: true
      })
    },
    innerCanceToCart: function () {
      this.setData({
        innerPopVisible: false
      })
    },
    // 加入购物车（完成）
    innerAddToCart: function () {
      this.setData({
        innerPopVisible: false
      })
    }
  }
})